﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NotepadDemo.Helps;
using NotepadDemo.Models;

namespace NotepadDemo.Controllers
{
    public class NotepadController : Controller
    {
        public ActionResult Index()
        {
            if (Request.HttpMethod == "GET")
            {
                ViewBag.fileName = Request["fileName"] ?? "";
                return View();
            }

            string fileName = Request["uri"];
            string serverPath = Server.MapPath("/Content/" + fileName);
            var entity = MyExtensionMethods.GetData(serverPath);
            if (Request["pwd"] == entity.Password)
                return Content(fileName);
            return Content("no");
        }

        [HttpPost]
        public ActionResult SetPassword()
        {
            string uri = Request["uri"];
            bool isLock = Request["lock"] == "False" ? false : true;
            DataModel model = new DataModel();
            model.Uri = uri;
            model.Content = Request["content"] ?? String.Empty;
            model.Password = Request["pwd"];
            model.IsLocked = isLock;
            var entity = JsonWrapper.Encode(model);
            if (MyExtensionMethods.FileSave(model.Uri, entity))
                return Content("ok");
            return Content("no");
        }


        [HttpPost]
        public ActionResult Save()
        {
            bool isLock = Request["lock"] == "False" ? false : true;
            DataModel model = new DataModel();
            model.Uri = Request["uri"];
            model.Content = Request["content"] ?? String.Empty;
            model.Password = Request["pwd"];
            model.IsLocked = isLock;
            var entity = JsonWrapper.Encode(model);
            if (MyExtensionMethods.FileSave(model.Uri, entity))
                return Content("ok");
            return Content("no");
        }
    }
}